<template>
    <Breadcrumb :bread-crumb-list="breadCrumbList" />
    <div class="zqy-seach-table ai-item">
        <div class="zqy-table-top">
            <el-button type="primary" @click="addData">
                添加
            </el-button>
            <div class="zqy-seach">
                <el-input
                    v-model="keyword"
                    placeholder="请输入搜索条件 回车进行搜索"
                    clearable
                    :maxlength="200"
                    @input="inputEvent"
                    @keyup.enter="initData(false)"
                />
            </div>
        </div>
        <LoadingPage :visible="loading" :network-error="networkError" @loading-refresh="initData(false)">
            <div class="zqy-table">
                <BlockTable :table-config="tableConfig" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <template #statusTag="scopeSlot">
                        <ZStatusTag :status="scopeSlot.row.status"></ZStatusTag>
                    </template>
                    <template #options="scopeSlot">
                        <div class="btn-group btn-group-msg">
                            <span
                                v-if="!scopeSlot.row.checkLoading"
                                @click="checkAiStatus(scopeSlot.row)"
                            >检测</span>
                            <el-icon
                                v-else
                                class="is-loading"
                            >
                                <Loading />
                            </el-icon>
                            <el-dropdown trigger="click">
                                <span class="click-show-more">更多</span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="editEvent(scopeSlot.row)">编辑</el-dropdown-item>
                                        <el-dropdown-item v-if="['ENABLE'].includes(scopeSlot.row.status)" @click="stopData(scopeSlot.row)">下线</el-dropdown-item>
                                        <el-dropdown-item v-else @click="publishData(scopeSlot.row)">启动</el-dropdown-item>
                                        <el-dropdown-item v-if="scopeSlot.row.aiType !== 'API' && ['ENABLE'].includes(scopeSlot.row.status)" @click="showRunLog(scopeSlot.row)">运行日志</el-dropdown-item>
                                        <el-dropdown-item @click="showDeployLog(scopeSlot.row)">部署日志</el-dropdown-item>
                                        <el-dropdown-item @click="deleteData(scopeSlot.row)">删除</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </template>
                </BlockTable>
            </div>
        </LoadingPage>
        <AddModal ref="addModalRef" />
        <ShowLog ref="showLogRef" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import Breadcrumb from '@/layout/bread-crumb/index.vue'
import LoadingPage from '@/components/loading/index.vue'
import { BreadCrumbList, TableConfig } from './list.config'
import { QueryAiItemList, AddAiItemData, UpdateAiItemData, DeployAiItemLogData, StopAiItemLogData, CheckAiItemData, DeleteAiItemData } from '@/services/ai-item.service'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import AddModal from './add-modal/index.vue'
import ShowLog from './show-log/index.vue'

interface ApiKey {
    apiKey: string
}

interface FormParams {
    name: string
    modelId: string
    remark: string
    authConfig: ApiKey
    id?: string
}

const keyword = ref<string>('')
const loading = ref<boolean>(false)
const networkError = ref<boolean>(false)
const addModalRef = ref<any>(null)
const showLogRef = ref<any>(null)
const timer = ref<any>(null)

const breadCrumbList = reactive(BreadCrumbList)
const tableConfig: any = reactive(TableConfig)

function initData(tableLoading?: boolean, type?: string) {
    loading.value = tableLoading ? false : true
    networkError.value = networkError.value || false
    QueryAiItemList({
        page: tableConfig.pagination.currentPage - 1,
        pageSize: tableConfig.pagination.pageSize,
        searchKeyWord: keyword.value
    }).then((res: any) => {
        tableConfig.tableData = res.data.content
        tableConfig.pagination.total = res.data.totalElements
        loading.value = false
        tableConfig.loading = false
        networkError.value = false
    }).catch(() => {
        tableConfig.tableData = []
        tableConfig.pagination.total = 0
        loading.value = false
        tableConfig.loading = false
        networkError.value = true
    })
}

function addData() {
    addModalRef.value.showModal((formData: FormParams) => {
        return new Promise((resolve: any, reject: any) => {
            AddAiItemData(formData).then((res: any) => {
                ElMessage.success(res.msg)
                initData()
                resolve()
            }).catch((error: any) => {
                reject(error)
            })
        })
    })
}
function editEvent(data: any) {
    addModalRef.value.showModal((formData: FormParams) => {
        return new Promise((resolve: any, reject: any) => {
            UpdateAiItemData(formData).then((res: any) => {
                ElMessage.success(res.msg)
                initData()
                resolve()
            }).catch((error: any) => {
                reject(error)
            })
        })
    }, data)
}

function publishData(data: any) {
    ElMessageBox.confirm('确定发布吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        DeployAiItemLogData({
            id: data.id
        }).then((res: any) => {
            ElMessage.success(res.msg)
            handleCurrentChange(1)
        }).catch(() => {})
    })
}

// 查看运行日志
function showRunLog(e: any) {
    showLogRef.value.showModal(e.id, 'run')
}

// 查看部署日志
function showDeployLog(e: any) {
    showLogRef.value.showModal(e.id, 'deploy')
}

function stopData(data: any) {
    ElMessageBox.confirm('确定下线吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        StopAiItemLogData({
            id: data.id
        }).then((res: any) => {
            ElMessage.success(res.msg)
            handleCurrentChange(1)
        }).catch(() => {})
    })
}

// 删除智能体
function deleteData(data: any) {
    ElMessageBox.confirm('确定删除该智能体吗？删除后将无法恢复。', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        DeleteAiItemData({
            id: data.id
        }).then((res: any) => {
            ElMessage.success(res.msg)
            initData()
        }).catch(() => {})
    })
}

// 检测智能体状态
function checkAiStatus(data: any) {
    // 设置加载状态
    data.checkLoading = true

    CheckAiItemData({
        id: data.id
    }).then((res: any) => {
        data.checkLoading = false
        ElMessage.success("检测成功")
    }).catch((error: any) => {
        data.checkLoading = false
    })
}

function inputEvent(e: string) {
    if (e === '') {
        initData()
    }
}

function handleSizeChange(e: number) {
    tableConfig.pagination.pageSize = e
    initData()
}

function handleCurrentChange(e: number) {
    tableConfig.pagination.currentPage = e
    initData()
}

onMounted(() => {
    tableConfig.pagination.currentPage = 1
    tableConfig.pagination.pageSize = 10
    initData()
    // 启动自动刷新定时器，每3秒刷新一次
    timer.value = setInterval(() => {
        initData(true, 'interval')
    }, 3000)
})

onUnmounted(() => {
    // 清理定时器
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})
</script>

<style lang="scss">
.ai-item {
    &.zqy-seach-table {
        .zqy-table {
            .btn-group-msg {
                justify-content: space-around;
            }
        }
    }
}
</style>